package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.domain.Category;
import com.itheima.domain.Setmeal;
import com.itheima.domain.SetmealDish;
import com.itheima.dto.SetmealDto;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 套餐管理
 */
@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {


    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 添加套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    //将数据从缓存中清除(清除所有的缓存数据)
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> saveDishs(@RequestBody SetmealDto setmealDto) {
        //多张表操作（复杂）
        setmealService.addSetmeal(setmealDto);
        return R.success("套餐保存成功了！");
    }

    /**
     * 分页
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R pageDishs(Integer page, Integer pageSize, String name) {
        //封装
        IPage<Setmeal> setmealPage = new Page<>(page, pageSize);
        //模糊查询
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);
        //分页
        setmealService.page(setmealPage, wrapper);
        //获取值
        long total = setmealPage.getTotal();
        List<Setmeal> records = setmealPage.getRecords();
        //map封装
        Map<String, Object> map = new HashMap<>();
        //转型
        map.put("total", (int) total);
        //list封装
        ArrayList<SetmealDto> list = new ArrayList<>();
        //赋值给另一个表中
        for (Setmeal setmeal : records) {
            SetmealDto dto = new SetmealDto();
            //复制
            BeanUtils.copyProperties(setmeal, dto);
            //获取值
            Long id = dto.getCategoryId();
            Category byId = categoryService.getById(id);
            dto.setCategoryName(byId.getName());
            //添加
            list.add(dto);
        }
        //把list集合封装进去
        map.put("records", list);

        //返回map集合（因为map集合包含了list集合）
        return R.success(map);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    //将数据从缓存中清除(清除所有的缓存数据)
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids) {
        setmealService.delectSetmeal(ids);
        return R.success("删除成功");
    }

    /**
     * 起售停售
     *
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    public R status(@RequestParam List<Long> ids,
                    @PathVariable Integer status) {
        setmealService.statusSetmeal(status, ids);
        return R.success("状态更新成功！");
    }


    /**
     * 回显菜品套餐
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R updata(@PathVariable Long id) {
        //根据套餐id查询套餐数据
        Setmeal byId = setmealService.getById(id);
        //根据套餐id查询套餐对应的菜品数据
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(wrapper);
        //将套餐和套餐菜品数据封装
        SetmealDto dto = new SetmealDto();
        //将  byId 和 setmealDishlist 数据封装到dto中
        BeanUtils.copyProperties(byId, dto);
        dto.setSetmealDishes(list);
        //  返回数据
        return R.success(dto);
    }

    /**
     * 修改套餐
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
/*    //将数据从缓存中清除(清除所有的缓存数据)
    @CacheEvict(value = "setmealCache", allEntries = true)*/
    public R updateSave(@RequestBody SetmealDto setmealDto) {
        setmealService.updateSave(setmealDto);
        return R.success("套餐修改成功");
    }


    /**
     * 首页展示（查询套餐内容）
     *
     * @param categoryId
     * @param status
     * @return
     */
    @GetMapping("/list")
    //查看缓存是否有数据，有则直接返回缓存数据，没有，则调用方法返回值把数据添加进去
    @Cacheable(value = "setmealCache", key = "#categoryId + '_' + #status")
    public R listByCategorydId(Long categoryId, Integer status) {
        //查询id值和status值
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Setmeal::getCategoryId, categoryId);
        wrapper.eq(Setmeal::getStatus, status);
        List<Setmeal> list = setmealService.list(wrapper);
        return R.success(list);
    }


}
